package com.rd.student.jike.class2.lihongming.week724_730.Day724;
import java.util.Random;
import java.util.concurrent.Semaphore;

/**
 * @Auther:Heinrich
 * @Date:2023/7/24-07-24-14:42
 * @Description:com.rd.student.jike.class2.lihongming.Day0724
 * @version:1.0
 */
public class TestSemaphore {
    //acquire()
    //获取一个令牌
    //在获取到令牌之前是阻塞状态
    //tryAcquire()
    //尝试获取令牌 可能成功 可能失败
    //release()
    //释放一个令牌，同时唤醒其他等待中的线程
    //getQueueLength()
    //获取等待中的线程数量
    //hasQueuedThreads
    //判断等待队列中是否还有线程
    private static Semaphore semaphore = new Semaphore(20);

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            try {
                Thread.sleep(new Random().nextInt(300));
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName()+
                            "来到停车场");
                    //返回可用的令牌数量
                    if(semaphore.availablePermits()==0){
                        System.out.println("车位不足请等待");
                    }
                    try {
                        semaphore.acquire();
                        System.out.println(Thread.currentThread().getName()+
                                " 进入停车场");
                        Thread.sleep(new Random().nextInt(4500));
                        System.out.println(Thread.currentThread().getName()+
                                " 开出停车场");
                        semaphore.release();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
            thread.start();
        }
    }
}

